$(function () {
    var username = $("#username");
    var password = $("#password");
    var ckb = $("#ckb");
    var sub = $("#sub");
    var registerBtn = $(".register-btn");
    var n = 0; //记录checkbox的点击状态

    ckb.on("click", function () {
        n++;
    })

    if (document.cookie) {
        var arr = document.cookie.split('; ');
        arr.forEach(function (elm, i) {
            console.log(elm);
            var item = elm.split('=');
            switch (item[0]) {
                case 'username':
                    username.val(item[1]);
                    break;
                case 'password':
                    password.val(item[1]);
                    break;
            }
        });
    }

    sub.on("click", function () {
        event.preventDefault();
        var d = new Date();
        d.setDate(d.getDate() + 3);

        if (n % 2) {
            document.cookie = "username=" + username.val() + ";expires = " + d;
            document.cookie = "password=" + password.val() + ";expires = " + d;
        }


        $.ajax({
            type: "post",
            url: "../lib/login.php",
            data: JSON.stringify({
                username: username.val(),
                password: password.val()
            }),
            dataType: "json",
            success: function (response) {
                if (response.login) {
                    document.cookie = "loginStatus=true";
                    alert("登陆成功，正在跳转...");
                    location.href = "../html/index1.html";
                } else {
                    alert("用户名或密码错误！");
                }
            }
        });
    })

    registerBtn.on("click", function () {
        location.href = "../html/register.html";
    })
})